import axios, { AxiosResponse } from "axios";
import { showMessage } from "./status";
import { headers } from "next/dist/client/components/headers";
// import { config } from 'process';

declare module "axios" {
  export interface AxiosResponse<T = any> extends Promise<T> {}
}

const Service = axios.create({
  timeout: 5000,
  method: "post",
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截
Service.interceptors.request.use((config) => {
  const token = localStorage.getItem("token");
  config.headers["Authorization"] = token;
  return config;
});

// 响应拦截
Service.interceptors.response.use(
  (response: AxiosResponse) => {
    const successStatus = [200, 201, 204];
    if (successStatus.includes(response.status)) {
      return Promise.resolve(response);
    } else {
      showMessage(response.status);
      return Promise.reject(response);
    }
  },
  (error: any) => {
    const { response } = error;
    if (response) {
      showMessage(response.status);
      return Promise.reject(response);
    } else {
      console.error("请求失败:", error);
    }
  }
);

export default Service;
